<template>
  <div class="app-container">
    <el-card>
      <div class="filter-container">
        <el-button type="primary" @click="handleCreate">新增</el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="forumList"
        border
        fit
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column prop="name" label="公司名称" />
        <el-table-column prop="industry" label="行业" />
        <el-table-column prop="context" label="想了解的内容" />
        <el-table-column label="参与人员" width="300">
          <template #default="{ row }">
            <el-tag
              v-for="(participant, index) in row.humans"
              :key="index"
              style="margin-right: 5px; margin-bottom: 5px"
            >
              {{ participant.name }} ({{ participant.position }})
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
            <el-button size="small" type="info" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        v-model:page="listQuery.page"
        v-model:limit="listQuery.size"
        :total="total"
        @pagination="fetchData"
      />

      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%" @close="resetForm">
        <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
          <el-form-item label="公司名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="行业" prop="industry">
            <el-input v-model="form.industry" />
          </el-form-item>
          <el-form-item label="想了解的内容" prop="context">
            <el-input v-model="form.context" type="textarea" :rows="3" />
          </el-form-item>
          <el-form-item label="参与人员" prop="humans" required>
            <div style="display: flex; gap: 20px; align-items: center">
              <div>
                <div v-for="(participant, index) in form.humans" :key="index">
                  <el-row :gutter="20">
                    <el-col :span="7">
                      <el-input v-model="participant.name" placeholder="姓名" />
                    </el-col>
                    <el-col :span="7">
                      <el-input v-model="participant.position" placeholder="职务" />
                    </el-col>
                    <el-col :span="7">
                      <el-input v-model="participant.phone" placeholder="电话" />
                    </el-col>
                    <el-col :span="3">
                      <el-button type="danger" @click="removeParticipant(index)">删除</el-button>
                    </el-col>
                  </el-row>
                </div>
              </div>
              <el-button type="primary" plain size="small" @click="addParticipant">
                添加参与人员
              </el-button>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </template>
      </el-dialog>
    </el-card>

    <el-dialog v-model="detailDialogVisible" title="详情" width="50%">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="公司名称">{{ form.name }}</el-descriptions-item>
        <el-descriptions-item label="行业">{{ form.industry }}</el-descriptions-item>
        <el-descriptions-item label="想了解的内容">{{ form.context }}</el-descriptions-item>
        <el-descriptions-item label="参与人员">
          <div
            v-for="(participant, index) in form.humans"
            :key="index"
            style="margin-bottom: 10px; border: 1px solid #ccc; padding: 10px; border-radius: 10px"
          >
            <p>姓名: {{ participant.name }}</p>
            <p>职务: {{ participant.position }}</p>
            <p>电话: {{ participant.phone }}</p>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { ListQuery } from "@/utils/request";
import { ForumForm } from "@/api/forum/forum";
import { useForumStore } from "@/store/modules/forum/forum";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import Pagination from "@/components/Pagination/index.vue";

const forumStore = useForumStore();

const loading = ref(false);
const forumList = ref<any[]>([]);
const total = ref(0);
const listQuery = reactive<ListQuery>({
  page: 1,
  size: 20,
});

const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const dialogTitle = ref("");
const formRef = ref<FormInstance>();
const form = reactive<ForumForm>({
  id: undefined,
  name: "",
  industry: "",
  context: "",
  humans: [
    {
      name: "",
      position: "",
      phone: "",
    },
  ],
});

const rules = reactive({
  name: [{ required: true, message: "请输入公司名称", trigger: "blur" }],
  industry: [{ required: true, message: "请输入行业", trigger: "blur" }],
  context: [{ required: true, message: "请输入想了解的内容", trigger: "blur" }],
  humans: [
    {
      validator: (_: any, value: any, callback: any) => {
        if (!value || value.length === 0) {
          callback(new Error("至少需要添加一个参与人员"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

onMounted(() => {
  fetchData();
});

async function fetchData() {
  loading.value = true;
  try {
    await forumStore.fetchForumList(listQuery);
    forumList.value = forumStore.forumList;
    total.value = forumList.value.length;
  } finally {
    loading.value = false;
  }
}

function handleCreate() {
  dialogTitle.value = "新增";
  dialogVisible.value = true;
}

function handleEdit(row: any) {
  dialogTitle.value = "编辑";
  dialogVisible.value = true;
  Object.assign(form, row);
}

async function handleDelete(row: any) {
  try {
    await ElMessageBox.confirm("确认删除该记录?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await forumStore.deleteForum(row.id);
    ElMessage.success("删除成功");
    fetchData();
  } catch (err) {
    console.log(err);
  }
}

function handleDetail(row: any) {
  Object.assign(form, row);
  detailDialogVisible.value = true;
}

function addParticipant() {
  form.humans.push({
    name: "",
    position: "",
    phone: "",
  });
}

function resetForm() {
  formRef.value?.resetFields();
  form.id = undefined;
  form.name = "";
  form.industry = "";
  form.context = "";
  form.humans = [
    {
      name: "",
      position: "",
      phone: "",
    },
  ];
}

async function submitForm() {
  try {
    await formRef.value?.validate();
    if (form.id) {
      form.humans = form.humans.map((i) => {
        return {
          name: i.name,
          position: i.position,
          phone: i.phone,
        };
      });
      await forumStore.updateForum(form);
      ElMessage.success("更新成功");
    } else {
      await forumStore.addForum(form);
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
    fetchData();
  } catch (err) {
    console.log(err);
  }
}

function removeParticipant(index: number) {
  ElMessageBox.confirm("确定删除该参与人员吗？", "提示", {
    type: "warning",
  })
    .then(() => {
      form.humans.splice(index, 1);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
      return;
    });
}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
</style>
